package icu.jogeen.fishbook.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author jogeen
 * @Date 14:28 2020/6/24
 * @Description
 */
public class TxtBookScanner implements BookScanner {

    private String filePath;
    private RandomAccessFile ra = null;
    private Long[] offsetIndex;
    private long totalLines;



    File file = null;

    public TxtBookScanner(String filePath) {
        file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            return;
        }
        Path path = Paths.get(file.getPath());
        try {
//            Stream<String> countStream = Files.lines(path, Charset.forName("utf-8"));
//            totalLines = countStream.count();
//            offsetIndex = new long[Integer.parseInt(totalLines + "")];
            List<Long> offsetIndexList =new ArrayList<>();
            this.filePath = filePath;
            ra = new BufferedRandomAccessFile(file, "r");//效率提交N倍，秒加载
            while ((ra.readLine()) != null) {
                offsetIndexList.add(ra.getFilePointer());
            }
            totalLines=offsetIndexList.size();
            offsetIndex=new Long[Integer.parseInt(totalLines + "")];
            offsetIndexList.toArray(offsetIndex);
            System.out.println("ss");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String bookName() {
        return file.getName();
    }

    @Override
    public long getBookSize() {
        return file.length();
    }

    @Override
    public long getTotalLines() {
        return totalLines;

    }



    @Override
    public List<String> getContentForPage(int pageNum, int pageSize) {
        List<String> list=new ArrayList<String>(pageSize);
        try {

            int index = (pageNum - 1) * pageSize;
            ra.seek(offsetIndex[index]);
            if(index+pageSize>totalLines){
                pageSize=((Long)(totalLines-index)).intValue();
            }
            for (int i = 0; i < pageSize; i++) {
                list.add(new String(ra.readLine().getBytes("ISO-8859-1"), "utf-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询内容所有的页码，并显示
     * 显示前5行结果
     * @param str
     * @param pageSize
     * @return
     */
    @Override
    public List<String> findContent(String str, int pageSize) {
        List<String> list=new ArrayList<>();
        try {
            Path path = Paths.get(file.getPath());
            Stream<String> countStream = Files.lines(path, Charset.forName("utf-8"));
            AtomicInteger idx= new AtomicInteger();
            list=countStream.map(line->{
                int i=idx.getAndIncrement();
                if(line.indexOf(str)!=-1){
                    int page=i/pageSize+1;
                    return (page+":"+line);
                }
                return null;
            }).filter(s->s!=null).limit(5).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) {
//        TxtBookScanner txtBookScaner = new TxtBookScanner("C:\\Users\\Administrator\\Downloads\\十日谈.txt");
        TxtBookScanner txtBookScaner = new TxtBookScanner("D:\\小说\\九星毒奶.txt");

        System.out.println(txtBookScaner.getBookSize());
        System.out.println(txtBookScaner.bookName());
        System.out.println(txtBookScaner.getTotalLines());
        System.out.println(txtBookScaner.getContentForPage(2, 10));
        System.out.println("-----");
        System.out.println(txtBookScaner.getContentForPage(3, 10));
        System.out.println("-----");
        System.out.println(txtBookScaner.getContentForPage(1, 10));
        System.out.println("-----");
        System.out.println(txtBookScaner.findContent("在我眼中，一视同仁", 10));

    }
}
